using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class PoolManager : MonoBehaviour
{
    private Transform poolParent;

    //对象池字典
    private Dictionary<string, PoolBase> poolsDic = new Dictionary<string, PoolBase>();

    private void Awake()
    {
        poolParent = this.transform.parent.Find("Pool");
    }

    /// <summary>
    /// 创建物体对象池
    /// </summary>
    /// <param name="name"></param>
    /// <param name="releaseTime"></param>
    public void CreatGameObjectPool(string name, float releaseTime)
    {
        CreateObjectPool<GameObjectPool>(name, releaseTime);
    }

    /// <summary>
    /// 创建资源对象池
    /// </summary>
    /// <param name="name"></param>
    /// <param name="releaseTime"></param>
    public void CreatAssetBundlePool(string name, float releaseTime)
    {
        CreateObjectPool<AssetPool>(name, releaseTime);
    }

    private void CreateObjectPool<T>(string poolName, float releaseTime) where T : PoolBase
    {
        if(!poolsDic.TryGetValue(poolName, out PoolBase pool)) 
        {
            GameObject gameObject = new GameObject(poolName);
            gameObject.transform.SetParent(poolParent);
            pool = gameObject.AddComponent<T>();
            pool.Init(releaseTime);
            poolsDic.Add(poolName, pool);
        }
    }

    //取出对象
    public Object Spwan(string poolName, string assetName)
    {
        //通过对象池名找到对应对象池，通过资源名找到对应对象池中的对应资源
        if(poolsDic.TryGetValue(poolName, out PoolBase pool))
        {
            return pool.Spwan(assetName);
        }
        return null;
    }

    //回收对象
    public void UnSpwan(string poolName, string assetName, Object asset) 
    {
        if(poolsDic.TryGetValue(poolName,out PoolBase pool))
        {
            pool.UnSpwan(assetName, asset);
        }
    }
}
